package org.linlinjava.litemall.admin.web;


import org.apache.commons.lang.StringUtils;
import org.linlinjava.litemall.admin.annotation.LoginAdmin;
import org.linlinjava.litemall.core.express.ExpressService;
import org.linlinjava.litemall.core.notify.NotifyService;
import org.linlinjava.litemall.core.notify.NotifyType;
import org.linlinjava.litemall.core.util.JacksonUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.LitemallOrder;
import org.linlinjava.litemall.db.service.LitemallConfigService;
import org.linlinjava.litemall.db.service.LitemallOrderService;
import org.linlinjava.litemall.db.util.OrderUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * 物流信息接口
 */
@RestController
@RequestMapping("/admin/express")
public class AdminExpressController {

    @Autowired
    ExpressService expressService;

    @Autowired
    LitemallConfigService configService;

    @Autowired
    LitemallOrderService orderService;

    @Autowired
    private NotifyService notifyService;

    @GetMapping("/orderCancelSurface")
    public Object orderCancelSurface (@LoginAdmin Integer adminId, String ShipperCode, String OrderCode, String ExpNo){
        if(adminId == null){
            return ResponseUtil.unlogin();
        }
        String result = null;
        try {
             result = expressService.orderCancelByJson(ShipperCode, OrderCode, ExpNo);

        } catch (Exception ex) {
            ex.printStackTrace();
        }

         return ResponseUtil.ok(result);
    }
    @PostMapping("generateSurface")
    public Object generateSurface(@LoginAdmin Integer adminId, @RequestBody String body){
        if(adminId == null){
            return ResponseUtil.unlogin();
        }

        String shipperCode =  JacksonUtil.parseString(body, "shipperCode");
        String orderCode = JacksonUtil.parseString(body, "orderCode");
        Integer payType = JacksonUtil.parseInteger(body, "payType");
        Integer expType = JacksonUtil.parseInteger(body, "expType");
        String receiverName = JacksonUtil.parseString(body, "receiverName");
        String receiverMobile = JacksonUtil.parseString(body, "receiverMobile");
        String receiverAddressArr[] = JacksonUtil.parseString(body, "receiverAddress").split("\\s");
        String receiverProvinceName = receiverAddressArr[0];
        String receiverCityName = receiverAddressArr[1];
        String receiverExpAreaName = receiverAddressArr[2];
        String receiverAddress = receiverAddressArr[3];
        String goodsName = JacksonUtil.parseString(body, "goodsName");

        String shipSn =  JacksonUtil.parseString(body, "shipSn");//圆通到付的才会有数据
        String lottery = JacksonUtil.parseString(body, "lottery");//抽奖发货的才会有数据
        Boolean shipper = JacksonUtil.parseBoolean(body, "shipper");//发货方
        String quantity = JacksonUtil.parseString(body, "quantity");
        String senderName = configService.findById(10000005).getValue();
        String senderMobile = configService.findById(10000006).getValue();
        String[] address = configService.findById(10000007).getValue().split("\\s");
        String senderProvinceName = address[0];

        String senderCityName = address[1];
        String senderExpAreaName = address[2];
        String senderAddress = address[3];
        String result = null;
        try {
            result = expressService.orderOnlineByJson(shipperCode, orderCode, payType,  expType, receiverName,  receiverMobile,
                    receiverProvinceName, receiverCityName, receiverExpAreaName, receiverAddress,  senderName,
                    senderMobile, senderProvinceName, senderCityName, senderExpAreaName, senderAddress,  goodsName, quantity);

        } catch (Exception ex) {
            ex.printStackTrace();
        }

        if (result != null) {
            Boolean Success = JacksonUtil.parseBoolean(result, "Success");

            if (Success) {

                String PrintTemplate = JacksonUtil.parseString(result, "PrintTemplate");

                Map<String, String> Order = JacksonUtil.parseObject(result, "Order", Map.class);

                String OrderCode = Order.get("OrderCode");
                String ShipperCode =expressService.getVendorName(Order.get("ShipperCode"));
                String LogisticCode =  Order.get("LogisticCode");
                 if (OrderCode == null || ShipperCode == null || LogisticCode == null) {
                    return ResponseUtil.badArgument();
                }

                 if(StringUtils.isEmpty(lottery)){
                     LitemallOrder order = orderService.queryByOrderSn(OrderCode);
                     if (order == null) {
                         return ResponseUtil.badArgument();
                     }
                     // 如果订单不是已付款状态，则不能发货
                     if (!order.getOrderStatus().equals(OrderUtil.STATUS_PAY)) {
                         return ResponseUtil.fail(403, "订单不能发货");
                     }

                     order.setOrderStatus(OrderUtil.STATUS_SHIP);
                     if("YTO".equals(shipperCode.toString()) && "2".equals(payType.toString())){
                         LogisticCode = shipSn;
                     }
                     order.setShipper(shipper);
                     order.setShipSn(LogisticCode);
                     order.setShipChannel(ShipperCode);
                     order.setShipTime(LocalDateTime.now());
                     orderService.update(order);
                 }
                String params = new String("{\"ordersn\":\"" + OrderCode + "\"}");
                notifyService.notifySmsTemplateSync(receiverMobile, NotifyType.DELIVERGOODS, params);
        }


        }
        return ResponseUtil.ok(result);
    }

    @PostMapping("confirmDelivery")
    public Object confirmDelivery(@LoginAdmin Integer adminId, @RequestBody String body){
        if(adminId == null){
            return ResponseUtil.unlogin();
        }

        String orderCode = JacksonUtil.parseString(body, "orderCode");//订单编号

        Boolean shipper = JacksonUtil.parseBoolean(body, "shipper");//发货方

        String shipSn = JacksonUtil.parseString(body, "shipSn");//物流单号

        String receiverMobile = JacksonUtil.parseString(body, "receiverMobile");//用户手机号

        if (orderCode == null || shipper == null || shipSn == null) {
            return ResponseUtil.badArgument();
        }

        LitemallOrder order = orderService.queryByOrderSn(orderCode);
        if (order == null) {
            return ResponseUtil.badArgument();
        }

        // 如果订单不是已付款状态，则不能发货
        if (!order.getOrderStatus().equals(OrderUtil.STATUS_PAY)) {
            return ResponseUtil.fail(403, "订单不能发货");
        }

        order.setOrderStatus(OrderUtil.STATUS_SHIP);

        order.setShipper(shipper);
        order.setShipSn(shipSn);
        order.setShipTime(LocalDateTime.now());
        orderService.update(order);
        String params = new String("{\"ordersn\":\"" + orderCode + "\"}");
        notifyService.notifySmsTemplateSync(receiverMobile, NotifyType.DELIVERGOODS, params);
        return ResponseUtil.ok();
    }
}
